package com.myorg.search;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.myorg.domain.SearchRequest;
import com.myorg.domain.SearchResult;
import com.myorg.service.SearchService;
import com.myorg.service.StartupService;

@WebServlet("/SearchDispatcher")
public class SearchDispatcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(SearchDispatcher.class);

	public SearchDispatcher() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		StartupService.touch();
		final String key = request.getParameter("key");
		final String filePath = request.getParameter("file");
		logger.info("key=" + key);
		logger.info("filePath=" + filePath);

		// final String uniquePath = createZnode();

		SearchResult rtn = new SearchService().dispatchSearch(new SearchRequest().setKey(key).setFilePaths(new String[] { filePath }),
				request.getContextPath(), request.getServerPort(), null);

		response.getWriter().write(new Gson().toJson(rtn));
		logger.info("Done");
	}
}
